package org.example.cloudalibaba.controller;

import cn.hutool.core.util.IdUtil;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.example.cloudalibaba.myhandler.CustomFallbackHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
public class FlowLimitController {
    @GetMapping("testA")
    public String testA() throws InterruptedException {
//        TimeUnit.SECONDS.sleep(1);// 模拟线程阻塞
        return "testA";
    }

    @GetMapping("testB")
    public String testB() throws InterruptedException {
//        TimeUnit.SECONDS.sleep(1);// 模拟线程阻塞
        return "testB";
    }

    // 服务降级RT策略测试接口：http://localhost:8401/testD
    @GetMapping("testD")
    public String testD() throws InterruptedException {
        TimeUnit.SECONDS.sleep(1);// 模拟线程阻塞
        String result = "testD：" + IdUtil.fastSimpleUUID();
        log.info(result);
        return result;
    }

    // 服务降级 异常比例/异常数 策略测试接口：http://localhost:8401/testE
    @GetMapping("testE")
    @SentinelResource(value = "testE", fallback = "defaultHandleBlock")
    public String testE() {
        int i = 10 / 0;
        String result = "testE：" + IdUtil.fastSimpleUUID();
        log.info(result);
        return result;
    }

    @GetMapping("testF")
    @SentinelResource(value = "testF",
            fallbackClass = CustomFallbackHandler.class,
            fallback = "defaultFallback")
    public String testF() {
        int i = 10 / 0;
        String result = "testF：" + IdUtil.fastSimpleUUID();
        log.info(result);
        return result;
    }


    // 热点限流 测试接口：http://localhost:8401/testHotkey?k1=v1&k2=v2
    @GetMapping("testHotkey")
    @SentinelResource(value = "testHotkey", blockHandler = "testHotkeyHandleBlock")
    public String testHotkey(
            @RequestParam(value = "k1", required = false) String k1,
            @RequestParam(value = "k2", required = false) String k2
    ) {
        String result = "testHotkey：" + IdUtil.fastSimpleUUID()
                + "\nk1:" + k1 + "\nk2:" + k2;
        log.info(result);
        return result;
    }

    public String testHotkeyHandleBlock(String k1, String k2, BlockException e) {
        return "testHotkeyHandleBlock: blocked!" + "\n" + IdUtil.fastSimpleUUID()
                + "\nk1:" + k1 + "\nk2:" + k2;
    }

    public String defaultHandleBlock() {
        return "defaultHandleBlock: " + IdUtil.fastSimpleUUID();
    }
}
